package com.easybenefit.UUService.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.view.View;
import android.webkit.GeolocationPermissions;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.easybeanfit.UUService.commutill.UUDialogUtill;
import com.easybeanfit.UUService.commutill.UUJsonUtil;
import com.easybeanfit.UUService.commutill.UULogUtil;
import com.easybeanfit.UUService.commutill.UUNetUtill;
import com.easybeanfit.UUService.commutill.UUSharedUtil;
import com.easybeanfit.UUService.commutill.UUToastUtil;
import com.easybeanfit.UUService.config.UUConfig;
import com.easybeanfit.UUService.config.UUDict;
import com.easybenefit.UUService.BaseActivity;
import com.easybenefit.UUService.MyApplication;
import com.easybenefit.UUService.R;
import com.easybenefit.UUService.model.HttpCouponBean;
import com.easybenefit.UUService.model.HttpCouponInfoBean;
import com.easybenefit.UUService.model.UserInfo;
import com.easybenefit.UUService.myinterface.IActivityInterface;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.RequestType;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.handler.UMWXHandler;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.weixin.view.WXCallbackActivity;

import org.apache.http.Header;

/**
 * 优惠券详情列表
 * type值是boolean true显示下架按钮   false 不显示
 * Created by 46595 on 2016/6/11.
 */
public class CouponsDetailActivity extends BaseActivity implements IActivityInterface, View.OnClickListener {
    private Button btn_back, btn_add;//返回和发布
    private TextView tv_title;
    private WebView webView;
    private ToggleButton tgb_distributed;//是否派发
    private ToggleButton tgb_union_distributed;//是否联盟派发
    private Button btn_unshelve;//下架
    private LinearLayout llt_bottom;
    private MyApplication myApplication;
    /**
     * 优惠券id
     */
    private String coupon_id;
    private ProgressDialog progressDialog;
    private ProgressDialog webProgressDialog;
    /**
     * 分享标题
     */
    private String umeng_title = "";
    /**
     * 分享图片
     */
    private String umeng_img = "";
    /**
     * 分享url
     */
    private String umeng_url = "";
    private UserInfo userInfo;
    private UMImage image;
    private Context context;
    private final int REQUEST_CODE_ASK_WRITE = 1;
    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onResult(SHARE_MEDIA platform) {
            if (platform.name().equals("WEIXIN_FAVORITE")) {
                Toast.makeText(CouponsDetailActivity.this, platform + " 收藏成功", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(CouponsDetailActivity.this, platform + " 分享成功", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(CouponsDetailActivity.this, platform + " 分享失败", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(CouponsDetailActivity.this, platform + " 分享取消", Toast.LENGTH_SHORT).show();
        }
    };


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE_ASK_WRITE:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    this.recreate();
                } else {
                    // Permission Denied
                    Toast.makeText(context, "获取权限失败", Toast.LENGTH_SHORT)
                            .show();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_coupons_detail);
        myApplication = (MyApplication) getApplication();
        myApplication.addActivity(this);
        initView();
        initData();
        initListener();
    }

    @Override
    public void initData() {
        context = this;
        boolean isshow = getIntent().getBooleanExtra("type", false);
        boolean noWX = getIntent().getBooleanExtra("noWX", false);
        userInfo = (UserInfo) UUSharedUtil.getObject(CouponsDetailActivity.this, UUConfig.UU_USERINFO_NAME, UserInfo.class);
        umeng_title = getIntent().getStringExtra("umeng_title");
        umeng_img = getIntent().getStringExtra("umeng_img");
        umeng_url = getIntent().getStringExtra("umeng_url");
        String url = getIntent().getStringExtra("url");
        if (isshow) {//是否显示状态修改栏
            llt_bottom.setVisibility(View.GONE);
        } else {
            llt_bottom.setVisibility(View.VISIBLE);
//            String is_col=getIntent().getStringExtra("is_col");
//            if(is_col.equals("1")){//是否为U卡券 1为U卡券，0不为U卡券
//                llt_bottom.setVisibility(View.GONE);
//            }
            coupon_id = getIntent().getStringExtra("coupon_id");
            getStatus();
        }
        btn_add.setText(getResources().getText(R.string.share));
        if (noWX) {//没有微信推广功能
            btn_add.setVisibility(View.GONE);
        } else {
            image = new UMImage(CouponsDetailActivity.this, umeng_img);
        }
        //初始化状态

        webProgressDialog = UUDialogUtill.getLoadingBar(CouponsDetailActivity.this, "正在加载请稍后....");
        webProgressDialog.show();


        WebSettings webSetting = webView.getSettings();
        webSetting.setDefaultTextEncodingName("utf-8");// 避免中文乱码
        webSetting.setGeolocationEnabled(true);
        webSetting.setJavaScriptEnabled(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setAllowFileAccess(true);// 启用或禁止WebView访问文件数据
        webSetting.setDatabaseEnabled(true);//启用数据库
        String dir = this.getApplicationContext().getDir("database", this.MODE_PRIVATE).getPath();//设置定位的数据库路径
        webSetting.setGeolocationDatabasePath(dir);
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webSetting.setCacheMode(WebSettings.LOAD_DEFAULT| WebSettings.LOAD_CACHE_ELSE_NETWORK);
        webView.setBackgroundColor(Color.TRANSPARENT);// 设置其背景为透明

        //启用地理定位
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onReceivedIcon(WebView view, Bitmap icon) {
                super.onReceivedIcon(view, icon);
            }
            @Override
            public void onGeolocationPermissionsShowPrompt(String origin,
                                                           GeolocationPermissions.Callback callback) {
                callback.invoke(origin, true, false);
                super.onGeolocationPermissionsShowPrompt(origin, callback);
            }
        });
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {

                CouponsDetailActivity.this.webProgressDialog.dismiss();
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
                UUToastUtil.showToast(context,"加载错误请重试！");
                CouponsDetailActivity.this.webProgressDialog.dismiss();
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                UULogUtil.e(context,"---------------"+url);
                CouponsDetailActivity.this.webProgressDialog.show();
                webView.loadUrl(url);
                return true;
            }
        });
        webView.loadUrl(url);
    }

    @Override
    public void initView() {
        webView = (WebView) findViewById(R.id.webView);
        btn_back = (Button) findViewById(R.id.finish_btn);
        tv_title = (TextView) findViewById(R.id.top_title);
        btn_add = (Button) findViewById(R.id.btn_add);
        btn_unshelve = (Button) findViewById(R.id.btn_unshelve);
        tgb_distributed = (ToggleButton) findViewById(R.id.tgb_distributed);
        tgb_union_distributed = (ToggleButton) findViewById(R.id.tgb_union_distributed);
        llt_bottom = (LinearLayout) findViewById(R.id.llt_bottom);
    }

    @Override
    public void initListener() {
        btn_add.setOnClickListener(this);
        btn_back.setOnClickListener(this);
        btn_unshelve.setOnClickListener(this);
        tgb_distributed.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String url = UUConfig.SERVER_BASE_URL + "updatedistr";
                RequestParams params = new RequestParams();
                boolean isChecked = tgb_distributed.isChecked();
                params.put("coupon_id", coupon_id);
                if (isChecked) {
                    params.put("coupon_distr", "1");
                } else {
                    params.put("coupon_distr", "0");
                }
                updateStatus(url, params);
            }
        });
        tgb_union_distributed.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String url = UUConfig.SERVER_BASE_URL + "updateunion";
                RequestParams params = new RequestParams();
                boolean isChecked = tgb_union_distributed.isChecked();
                params.put("coupon_id", coupon_id);
                if (isChecked) {
                    params.put("coupon_union", "1");
                } else {
                    params.put("coupon_union", "0");
                }
                updateStatus(url, params);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.finish_btn:
                finish();
                break;
            case R.id.btn_add:
                new ShareAction(CouponsDetailActivity.this).setDisplayList(SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE)
                        .withTitle(umeng_title)
                        .withText(umeng_title)
                        .withMedia(image)
                        .withTargetUrl(umeng_url)
                        .setCallback(umShareListener)
                        .open();
                break;

            case R.id.btn_unshelve:
                final String url = UUConfig.SERVER_BASE_URL + "newcoustate";
                final RequestParams params = new RequestParams();
                params.put("coupon_id", coupon_id);
                params.put("coupon_status", 2);//下架
                params.put("mer_id", userInfo.getMer_id());
                new AlertDialog.Builder(context).setTitle("系统提示")
                        .setMessage("该优惠券下架后将无法再次上架，但是已被领取的券在有效期内仍可继续使用，确认下架吗？").
                        setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                cancelCoup(url, params);
                            }
                        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                }).show();
                break;

        }
    }

    /**
     * 更新优惠券状态
     *
     * @param url
     * @param params
     */
    public void updateStatus(String url, RequestParams params) {
        if (!UUNetUtill.isConnected(CouponsDetailActivity.this)) {
            UUToastUtil.showToast(CouponsDetailActivity.this, UUDict.NOT_INTERNET);
        } else {
            AsyncHttpClient client = new AsyncHttpClient();
            client.post(url, params, new AsyncHttpResponseHandler() {
                @Override
                public void onStart() {
                    progressDialog = UUDialogUtill.getLoadingBar(CouponsDetailActivity.this, "正在操作请稍后....");
                    progressDialog.show();
                }

                @Override
                public void onFinish() {
                    progressDialog.dismiss();
                }

                @Override
                public void onSuccess(int i, Header[] headers, byte[] bytes) {
                    String content = new String(bytes);
                    HttpCouponBean http = (HttpCouponBean) UUJsonUtil.fromJson(content, HttpCouponBean.class);
                    UUToastUtil.showToast(CouponsDetailActivity.this, http.getMessage());
                }

                @Override
                public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {

                }
            });
        }
    }

    /**
     * 下架优惠券
     *
     * @param url
     * @param params
     */
    public void cancelCoup(String url, RequestParams params) {
        if (!UUNetUtill.isConnected(CouponsDetailActivity.this)) {
            UUToastUtil.showToast(CouponsDetailActivity.this, UUDict.NOT_INTERNET);
        } else {
            AsyncHttpClient client = new AsyncHttpClient();
            client.post(url, params, new AsyncHttpResponseHandler() {
                @Override
                public void onStart() {
                    progressDialog = UUDialogUtill.getLoadingBar(CouponsDetailActivity.this, "正在操作请稍后....");
                    progressDialog.show();
                }

                @Override
                public void onFinish() {
                    progressDialog.dismiss();
                }

                @Override
                public void onSuccess(int i, Header[] headers, byte[] bytes) {
                    String content = new String(bytes);
                    HttpCouponBean http = (HttpCouponBean) UUJsonUtil.fromJson(content, HttpCouponBean.class);
                    CouponsDetailActivity.this.finish();
                }

                @Override
                public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {

                }
            });
        }
    }

    /**
     * 初始化优惠券
     */
    public void getStatus() {
        if (!UUNetUtill.isConnected(CouponsDetailActivity.this)) {
            UUToastUtil.showToast(CouponsDetailActivity.this, UUDict.NOT_INTERNET);
        } else {
            AsyncHttpClient client = new AsyncHttpClient();
            String url = UUConfig.SERVER_BASE_URL + "coustatus";
            RequestParams params = new RequestParams();
            params.put("mer_id", userInfo.getMer_id());
            params.put("coupon_id", coupon_id);
            client.post(url, params, new AsyncHttpResponseHandler() {
                @Override
                public void onStart() {
                    progressDialog = UUDialogUtill.getLoadingBar(CouponsDetailActivity.this, "正在操作请稍后....");
                    progressDialog.show();
                }

                @Override
                public void onFinish() {
                    progressDialog.dismiss();
                }

                @Override
                public void onSuccess(int i, Header[] headers, byte[] bytes) {
                    String content = new String(bytes);
                    HttpCouponInfoBean reponseBean = (HttpCouponInfoBean) UUJsonUtil.fromJson(content, HttpCouponInfoBean.class);
                    //是否允许派发
                    if (UUDict.ACEEPT.equals(reponseBean.getData().getCoupon_distr())) {
                        tgb_distributed.setChecked(true);
                    } else {
                        tgb_distributed.setChecked(false);

                    }
                    //是否允许联盟派发
                    if (UUDict.ACEEPT.equals(reponseBean.getData().getCoupon_union())) {
                        tgb_union_distributed.setChecked(true);
                    } else {
                        tgb_union_distributed.setChecked(false);

                    }
                    if (UUDict.IS_UCARD.equals(reponseBean.getData().getIsqiang()+"")) {//为字符串
                        llt_bottom.setVisibility(View.GONE);
                    }
                }

                @Override
                public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {

                }
            });
        }
    }
}
